$.validator.setDefaults({
    submitHandler: fb_submit
});

$(function(){

    $("#fbform").validate({
        rules: {
            name: {
                required: true,
                minlength: 2 
            },
            email: {
                required: true,
                email: true
            },
            comment: {
                required: true,
                minlength: 5
            }
        },
        messages: {
            name: "Please enter a name",
            email: "Please enter a valid email address",
            comment: "<br>Please provide some comment (min. 5 characters)"
        }
    });

    $("#feedback").dialog({ disabled: true, autoOpen: false, modal: true, 
                          resizable: false, draggable: false });
});

function fb_submit() {
    var app = new Object();
    app.name = $("input[name='name']").val();
    app.email = $("input[name='email']").val();
    app.comment = $("#fcomm").val();

    $.ajax({
        type: "POST",
        url: "/feedback",
        data: app,
        async: false,
        success: function(msg){
          $('#feedback').dialog('close');
          $("input[name='name']").val("");
          $("input[name='email']").val("");
          $("#fcomm").val("");
        },
        error: function(msg){
          alert("Your comment could not be submitted. Please refresh the page and try again");
          $('#feedback').dialog('close');
        }
    });
}

function writeFeedback()
{
    $('#feedback').html(' \
      <form class="" id="fbform" method="post" action=""> \
     <p> \
       <label for="fname">Name</label><br> \
       <input id="fname" name="name" size="25"/> \
     </p> <p> \
       <label for="femail">Email</label><br> \
       <input id="femail" name="email" size="25"/> \
     </p> <p> \
       <label for="fcomm">Comment</label><br> \
       <textarea id="fcomm" name="comment" cols=25 rows=5></textarea> \
     </p> <p> \
       <input name="submit" type="submit" value="Submit"/> \
     </p> </form> ');
}

function openFeedback()
{
    $('#feedback').dialog('open');
}
